package com.hmdp.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 店铺类型查询
     * @return
     */
    @Override
    public Result queryTypeList() {
        String key = CACHE_SHOP_TYPE_KEY;
        //1.从redis中查询店铺类型list缓存
        List<String> shopTypeJson = stringRedisTemplate.opsForList().range(key, 0, -1);
        //2.判断是否存在
        if (CollectionUtil.isNotEmpty(shopTypeJson)) {
            //3.存在，返回redis缓存
            List<ShopType> list = JSONUtil.toList(shopTypeJson.toString(), ShopType.class);
            Collections.sort(list,((o1, o2) -> o1.getSort()- o2.getSort()));
            return Result.ok(list);
        }

        //4.不存在，查询数据库
        List<ShopType> shopTypes = query().orderByAsc("sort").list();
        //5.判断数据库中数据是否存在
        if (CollectionUtil.isEmpty(shopTypes)) {
            //6.不存在，直接报错
            return Result.fail("店铺类型不存在");
        }

        //7.存在，将查询到的信息写入redis中
        List<String> shopTypesJson = shopTypes.stream().map(JSONUtil::toJsonStr).collect(Collectors.toList());

        stringRedisTemplate.opsForList().rightPushAll(key,shopTypesJson);
        //8.返回
        return Result.ok(shopTypes);
    }
}
